<?php
class Article extends Admin_Controller{
	public function __construct(){
		parent::__construct();
		$this->load->Model(array("Marticle","Mcatalogue","Msection","Mgallery"));
	}
	public function index(){
		$this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
		$this->breadcrumb->append_crumb(trans('breadcrumb_article'),base_url().'admincp/article');
		if($this->input->is_ajax_request()){
            $output = $this->Marticle->listArticle();
            $this->output->set_output(json_encode($output));
        }else{
            $data['template']="article/view";
            $data['title_page']='<i class="icon20 i-file-6"></i> '.trans('title_article');
			$this->load->view("admincp/template",$data);
        }
	}
	public function add(){
		$this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
		$this->breadcrumb->append_crumb(trans('breadcrumb_article'),base_url().'admincp/article');
		$this->breadcrumb->append_crumb('Create Article',base_url().'admincp/article/add');
		$data['template']="article/add";
		$data['title_page']='<i class="icon20 i-plus-circle-2"></i> '.trans('title_article_add');
		$data['section']=$this->Msection->list_all();
		$data['gallery']=$this->Mgallery->list_all();
		$dataLang = $this->registry->get('language');
    	$data['language'] = $dataLang;
		if($this->input->server('REQUEST_METHOD') == "POST"){

			$data_insert = array(
				'art_author' => $this->session->userdata['ses_admin'],
				'cata_id' => $this->input->post('catalogue'),
				'sec_id' => $this->input->post('section'),
				'date_add' => date('Y-m-d',time()), 
			);

			$this->Marticle->insert($data_insert);
			$id = $this->db->insert_id();

			$dataInsertMain = array();
			$dataInsertSub = array();
			foreach($dataLang as $lang){
				$art_title = $this->input->post('art_title_'.$lang['lang_code']);
				// $art_title_url = mb_strtolower(rtrim($art_title));
				// $art_title_url = change_alias($art_title_url);
				$dataInsertMain[] = array(
					'art_id' => $id,
					'lang_id' => $lang['id'],
					'art_title' => $art_title,
					'art_content' => $this->input->post('art_content_'.$lang['lang_code']),	
				);

				$dataSubTitle = $this->input->post('sub_title_'.$lang['lang_code']);
				$dataGalleryId = $this->input->post('gallery_id_'.$lang['lang_code']);				
				foreach($dataSubTitle as $key => $title){
					if($title != ''){
						$dataInsertSub[] = array(
							'art_id' => $id,
							'lang' => $lang['id'],
							'title' => $title,
							'gallery_id' => $dataGalleryId[$key]
						);
					}
				}
			}

			$this->db->insert_batch('tpt_article_content',$dataInsertMain);
			$this->db->insert_batch('tpt_sub_article',$dataInsertSub);
			
			$this->session->set_flashdata(array("success"=>trans('message_create_successfully')));
			$this->cache->delete_group('article_');
			redirect(base_url()."admincp/article");
		}
		$this->load->view("admincp/template",$data);
	}
	
	public function edit(){
		$id=$this->uri->segment(5);
		$this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
		$this->breadcrumb->append_crumb(trans('breadcrumb_article'),base_url().'admincp/article');
		$this->breadcrumb->append_crumb('Edit Article',base_url().'admincp/article/edit/id/'.$id);
		$data['template']="admincp/article/edit";
		$data['title_page']='<i class="icon20 i-pen-2"></i> '.trans('title_article_edit');
		$data['section']=$this->Msection->list_all();
		$data['info']=$this->Marticle->get_data($id);
		$dataLang = $this->registry->get('language');
		$data['language'] = $dataLang;
		foreach ($dataLang as $lang) {	
			$data['infoSub'][$lang['lang_code']]=$this->Marticle->get_sub_data($id, $lang['id']);
		}
		$data['gallery']=$this->Mgallery->list_all();
		$path_upload = 'assets/filemanager/article/';
		if($this->input->server('REQUEST_METHOD') == "POST"){			
			$dataUpdate = array(
				'cata_id' => $this->input->post('catalogue'),
				'sec_id' => $this->input->post('section'),
				'date_edit' => date('Y-m-d',time()), 
			);

			$this->db->where('art_id',$id);
			$this->db->update('tpt_article', $dataUpdate);

			$dataUpdateMain = array();
			$dataInsertSub = array();
			$dataUpdateSub = array();
			foreach($dataLang as $lang){
				$art_title = $this->input->post('art_title_'.$lang['lang_code']);
				// $art_title_url = mb_strtolower(rtrim($art_title));
				// $art_title_url = change_alias($art_title_url);
				$art_content = $this->input->post('art_content_'.$lang['lang_code']);
				$art_content = str_replace('../../../../', base_url(), $art_content);
				$dataUpdateMain = array(
					'art_title' => $art_title,
					'art_content' => $art_content,
				);
				$this->db->where('art_id',$id);
				$this->db->where('lang_id',$lang['id']);
				$this->db->update('tpt_article_content', $dataUpdateMain);

				$dataSubTitle = $this->input->post('sub_title_'.$lang['lang_code']);
				if(!empty($dataSubTitle)){
					$dataGalleryId = $this->input->post('gallery_id_'.$lang['lang_code']);				
					foreach($dataSubTitle as $key => $title){
						if($title != ''){
							$dataInsertSub[] = array(
								'art_id' => $id,
								'lang_id' => $lang['id'],
								'title' => $title,
								'gallery_id' => $dataGalleryId[$key]
							);
						}
					}
				}

				$dataSubTitleOld = $this->input->post('sub_title_old_'.$lang['lang_code']);
				if(!empty($dataSubTitleOld)){
					$dataGalleryIdOld = $this->input->post('gallery_id_old_'.$lang['lang_code']);
					$dataId = $this->input->post('dataId_'.$lang['lang_code']);
					$dataFinalSubTitleOld = array();
					foreach($dataSubTitleOld as $key => $title){
						if($title != ''){
							$dataFinalSubTitleOld[] = array(
								'id' => $dataId[$key],
								'lang_id' => $lang['id'],
								'title' => $title,
								'gallery_id' => $dataGalleryIdOld[$key]
							);
						}
					}
					$this->db->update_batch('tpt_sub_article', $dataFinalSubTitleOld, 'id'); 
				}
			}
			// $this->Marticle->update($dataUpdate,$id);

			if(!empty($dataInsertSub)){
				$this->db->insert_batch('tpt_sub_article',$dataInsertSub);
			}

			$this->session->set_flashdata(array("success"=>trans('message_edit_successfully')));
			redirect(base_url()."admincp/article");	
		}
		$this->load->view("admincp/template",$data);
	}
	
	public function delete(){
		$id = $this->uri->segment(5);
		$this->Marticle->delete($id);
		$this->session->set_flashdata(array("success"=>trans('message_delete_successfully')));
		redirect(base_url()."admincp/article");	
	}

	public function process(){
		if($this->input->is_ajax_request()){
			$id = $this->input->post("sec_id");
			$cata_id = $this->input->post("cata_id");
			$data = $this->Mcatalogue->list_all_by_sec_id($id);
			$html = '';
			foreach ($data as $value) {
				if($cata_id == $value['cata_id']){
					$html .= '<option value="'.$value['cata_id'].'" selected="selected">'.$value['cata_name'].'</option>';
				}else{
					$html .= '<option value="'.$value['cata_id'].'">'.$value['cata_name'].'</option>';
				}
			}
			$respone['html'] = $html;
			echo json_encode($respone);
		}
	}

	public function check(){
		if($this->input->is_ajax_request()){
			$id = $this->input->post("id");
			$status = $this->input->post("status");
			$active = $this->input->post("active");
			$deactive = $this->input->post("deactive");
			if($status == $active){
				$html = $deactive;
				$check = '0';				
			}
			if($status == $deactive){
				$html = $active;
				$check = '1';
			}
			$data['art_check'] = $check;
			$this->Marticle->update($data, $id);
			echo $html;
		}
	}

	public function getMore(){
		if($this->input->is_ajax_request()){
			$lang = $this->input->post('lang');
			$gallery=$this->Mgallery->list_all();
			$html = '<div class="form-group">
                    <label for="grid" class="col-lg-2 control-label">'.trans('title_sub_art_title').'</label>
                    <div class="col-lg-10">
                        <div class="col-lg-6">
                            <input type="text" name="sub_title_'.$lang.'[]" class="form-control">
                        </div>
                        <div class="col-lg-5">
                            <select class="select2" name="gallery_id_'.$lang.'[]">
                                <option></option>';
									foreach($gallery as $gal){
										$html .= ' <optgroup label="'.$gal['name'].'">';
										foreach($gal['items'] as $item){
											if($sub['gallery_id'] == $item['gallery_id']){
												$html .= '<option value="'.$item['gallery_id'].'" selected="selected">'.$item['gallery_name'].'</option>';
											}else{
												$html .= '<option value="'.$item['gallery_id'].'">'.$item['gallery_name'].'</option>';
											}
										}
										$html .= ' </optgroup>';
									}
                            $html .= '</select>
                        </div>
                        <div class="col-lg-1"><i class="icon16 i-close deleteSub" style="margin-top:10px"></i></div>
                    </div>
                </div>';
            $respone['html'] = $html;
            echo json_encode($respone);
		}
	}

	public function deleteSub(){
		if($this->input->is_ajax_request()){
			$id = $this->input->post("id");
			$this->db->where('id',$id);
			$this->db->delete('tpt_sub_article');
		}
	}
}